package xyz.lwm.lazycat.netpipe.configure;

import xyz.lwm.lazycat.annotation.Bean;
import xyz.lwm.lazycat.annotation.Configuration;
import xyz.lwm.lazycat.netpipe.common.msgs.MessageHandlerRegistry;
import xyz.lwm.lazycat.netpipe.setting.AuthSetting;
import xyz.lwm.lazycat.utility.R;
import xyz.lwm.lazycat.utility.ThrowableUtil;
import xyz.lwm.lazycat.web.Controllable;
import xyz.lwm.lazycat.web.Exceptionable;
import xyz.lwm.lazycat.web.settings.ServerSetting;

/**
 * 配置类
 *
 * @author lwm
 */
@Configuration
public class NetpipeConfig {

    @Bean
    public Controllable authHandlerControllable(ServerSetting serverSetting, AuthSetting authSetting) {
        return router -> router.before(new AuthFilter(serverSetting.getContextPath(), authSetting.getPassableUrls()));
    }

    @Bean
    public Exceptionable exceptionAdaptor() {
        return exceptionMapper ->
                exceptionMapper.register(Exception.class, (e, ctx) -> {
                    Throwable unwrapped = ThrowableUtil.unwrap(e);
                    ctx.json(R.fail(unwrapped.getMessage()));
                });
    }

    @Bean
    public MessageHandlerRegistry messageHandlerRegistry() {
        return new MessageHandlerRegistry();
    }

}
